package com.share.base.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author 小赵
 * @version 1.0
 * @data 2024-12-12 17:51
 * 用于创建和验证 JWT
 */
@Slf4j
public class JWTUtil {
    private static final String JWT_KEY = "lc_key";

    private static final ThreadLocal<ThreadLocalModel> threadLocalModel = new ThreadLocal<>();

    // 创建 JWT
    public static String createToken(Long user_id, Long file_id, Long bin_id) {
        long expireTimeMillis = TimeUnit.DAYS.toMillis(1);
        Date expireDate = new Date(System.currentTimeMillis() + expireTimeMillis);

        return JWT.create()
                .setPayload("user_id", user_id)
                .setPayload("file_id", file_id)
                .setPayload("bin_id", bin_id)
                .setExpiresAt(expireDate)
                .setKey(JWT_KEY.getBytes())
                .sign();
    }

    // 验证 JWT
    public static boolean verifyToken(String token) {
        try {
            System.out.println("Token: " + token);
            JWT jwt = JWT.of(token);
            System.out.println("JWT Payload: " + jwt.getPayload().toString());
            if (jwt.setKey(JWT_KEY.getBytes()).verify()) {
                ThreadLocalModel model = new ThreadLocalModel();
                model.setUserID(((Number) jwt.getPayload("user_id")).longValue());
                model.setFileID(((Number) jwt.getPayload("file_id")).longValue());
                model.setBinID(((Number) jwt.getPayload("bin_id")).longValue());
                threadLocalModel.set(model);
                System.out.println("ThreadLocalModel set successfully: " + model);
                return true;
            }
        } catch (JWTException e) {
            System.err.println("JWT token verification error: " + e.getMessage());
            return false;
        }
        return false;
    }

    // 从Token中获取用户ID
    public static Optional<Long> getUserIdFromToken(String token) {
        try {
            JWT jwt = JWT.of(token);
            return Optional.of(((Number) jwt.getPayload("user_id")).longValue());
        } catch (Exception e) {
            log.error("从Token中获取用户ID时出错: {}", e.getMessage());
            return Optional.empty();
        }
    }

    //设置放入到ThreadLocal
    public static void setUserId(Long userId) {
        ThreadLocalModel model = getThreadLocalModel();
        if (model == null) {
            model = new ThreadLocalModel();
        }
        model.setUserID(userId);
        threadLocalModel.set(model);
    }


    // 获取 ThreadLocalModel
    public static ThreadLocalModel getThreadLocalModel() {
        return threadLocalModel.get();
    }

    // 清理 ThreadLocal
    public static void clear() {
        threadLocalModel.remove();
    }
}
